package com.wyzz.hr.base;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.wyzz.hr.util.Environment;

import java.awt.Font;
import java.awt.FontMetrics;
import java.io.*;
import java.util.UUID;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.apache.log4j.Logger;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class BasePdfExport {

	public BasePdfExport() {
	}

	public static String pdfExport(String content) {
		String pdfFileName = (new StringBuilder()).append("export_").append(
				UUID.randomUUID().toString()).append(".pdf").toString();
		String fileNameWithPath = (new StringBuilder()).append(
				Environment.getFileHome()).append(pdfFileName).toString();
		System.out.println(Environment.getFileHome());
		System.out.println(fileNameWithPath);
		try {
			OutputStream os = new FileOutputStream(fileNameWithPath);
			ITextRenderer renderer = new ITextRenderer();
			renderer.setDocumentFromString(content);
			String resourceHome = Environment.getResourceHome();
			renderer.getSharedContext().setBaseURL(
					(new StringBuilder()).append("file:/").append(resourceHome)
							.append("images/").toString());
			System.out.println(resourceHome);
			renderer.layout();
			renderer.createPDF(os);
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return fileNameWithPath;
	}

	public static String processWrap(String text, int width, int cellpadding,
			int fontSize) {
		if (text == null)
			return null;
		Font f = new Font("SIMSUN", 0, fontSize);
		JComponent t = new JLabel();
		FontMetrics fm = t.getFontMetrics(f);
		int currentRowWidth = 0;
		for (int j = 0; j < text.length(); j++) {
			String tempChar = text.substring(j, j + 1);
			int charWidth = fm.stringWidth(tempChar);
			currentRowWidth += charWidth;
			if (currentRowWidth > width - 2 * cellpadding) {
				text = (new StringBuilder()).append(text.substring(0, j))
						.append("<br/>").append(text.substring(j)).toString();
				j += 5;
				currentRowWidth = 0;
			}
		}

		return text;
	}

	private static final Logger logger = Logger
			.getLogger(com.wyzz.hr.bo.impl.TemplateServiceFreeMarkerImpl.class);

}
